from django.shortcuts import render
from home import models, homeser
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.cache import cache


# Create your views here.

class TopNavView(APIView):
    def get(self, request):
        navkey = 'topnavlist'
        catchdata = cache.get(navkey)
        if catchdata:
            return Response({"msg": "ok", "data": catchdata})
        pos = request.query_params.get('pos')
        navlist = models.NavModel.objects.filter(position=1, isshow=True).order_by('order')
        ser = homeser.NavSer(navlist, many=True)
        cache.set(navkey, ser.data, 3600)
        return Response({"msg": "ok", "data": ser.data})


class BottomNavView(APIView):
    def get(self, request):
        navkey = 'bottomtopnavlist'
        catchdata = cache.get(navkey)
        if catchdata:
            return Response({"msg": "ok", "data": catchdata})
        pos = request.query_params.get('pos')
        navlist = models.NavModel.objects.filter(position=0, isshow=True).order_by('order')
        ser = homeser.NavSer(navlist, many=True)
        cache.set(navkey, ser.data, 3600)
        return Response({"msg": "ok", "data": ser.data})


class BannerView(APIView):
    def get(self, request):
        cache_key = 'bannerdata'
        cached_response = cache.get(cache_key)
        if cached_response:
            return Response({"msg": "ok", "data": cached_response})
        bannerlist = models.BannerModel.objects.filter(isshow=True).order_by('order')
        ser = homeser.BannerSer(bannerlist, many=True)
        cache.set(cache_key, ser.data, 3600)
        return Response({"msg": "ok", "data": ser.data})
